package com.dq.utils;

import com.dq.mapper.QQFriendMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: Dang Qi
 * @Date: 2021/5/8 15:30
 * @Description:
 */
public class MybatisUtils {
    public static void main(String[] args) {
        SqlSession sqlSession = getSqlSession();
        QQFriendMapper mapper = sqlSession.getMapper(QQFriendMapper.class);
        mapper.getFriend("1").forEach(System.out::println);
        sqlSession.close();
    }
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try{
            //第一步，获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    //既然有了 SqlSessionFactory，顾名思义，我们可以从中获得 SqlSession 的实例。
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    // 通过 SqlSession 实例来直接执行已映射的 SQL 语句
    public static SqlSession getSqlSession(){
        //添加true自动提交事务
        return sqlSessionFactory.openSession(true);
    }
}
